package com.cheems.cheems_spring_ai.config;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

@Configuration
@RequiredArgsConstructor
public class AIConfigOllama {

    final OllamaChatModel model;

    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        // 使用 SimpleVectorStore 的构建器模式创建实例
        return SimpleVectorStore
                .builder(embeddingModel).build();
    }

    @Bean
    CommandLineRunner initVectorStore( VectorStore vectorStore, @Value("classpath:rag/henau.txt") Resource resourceFile) {
        return args -> {
            vectorStore.write(  //写入数据库
                    new TokenTextSplitter().transform( //转换
                            new TextReader(resourceFile).read()//读取文件
                    )
            );
        };
    }

    // 构造历史对话和默认角色
    @Bean
    ChatClient chatClient(VectorStore vectorStore) {
        return ChatClient.builder(model)
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .build();
    }

}